package yl.hs.bmipfull.service.salemanage.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.salemanage.*;
import yl.hs.bmipfull.daos.system.IUserInfoDao;
import yl.hs.bmipfull.pojo.salemanage.BuildProjectInfoEntity;
import yl.hs.bmipfull.pojo.salemanage.ContractProductPriceAdjustRecordEntity;
import yl.hs.bmipfull.pojo.salemanage.SaleContractEntity;
import yl.hs.bmipfull.pojo.salemanage.SaleSysTagsEntity;
import yl.hs.bmipfull.pojo.system.UserInfoEntity;
import yl.hs.bmipfull.service.finance.IContractAccountService;
import yl.hs.bmipfull.service.salemanage.*;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.SearchFilterEngine;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.RelationType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;

import java.util.*;

/**
 * SaleContractServiceImpl
 *
 * @author 谢东 2021-05-17
 * @category
 */
@Service
public class SaleContractServiceImpl extends SaleBaseService implements ISaleContractService {
    @Autowired
    ISaleContractDao dao;
    @Autowired
    IContractControlInfoService controlService;
    @Autowired
    private ICustomerInfoService customerService;
    @Autowired
    private IBuildProjectInfoService buildProjectInfoService;

    @Autowired
    private ICustomerUserDao customerUserDao;

    @Autowired
    ILinkerInfoDao linkerInfoDao;
    @Autowired
    IUserInfoDao infoDao;
    @Autowired
    private IContractProductPriceAdjustDao productPriceAdjustDao;
    @Autowired
    IContractAccountService accountService;

    @Override
    public List<SaleContractEntity> queryList(PageQuery pageQuery) throws Exception {
        pageQuery.checkSortSides(SaleContractEntity.class);
        var data = dao.queryList(pageQuery.getQuery());
        return data;
    }

    @Override
    public List<SaleContractEntity> queryList() throws Exception {
        return queryList(new PageQuery());
    }

    @Override
    public List<Object> queryListAll(PageQuery pageQuery) throws Exception {
        pageQuery.checkSortSides(SaleContractEntity.class);
        var data = dao.queryList(pageQuery.getQuery());
        List<Object> list = new ArrayList<>();
        for (SaleContractEntity datum : data) {
            var info = infoDao.findBySN(datum.getSalerSN());
            var entity = datum.toMap();
            if(info!=null){
                entity.put("salerPhone",info.getMobileNum());
            }else {
                entity.put("salerPhone","");
            }
            list.add(entity);
        }
        return list;
    }
    @Override
    public PageResult<Map<String,Object>> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        var user = HsApp.getCurrent();
        pageQuery.checkSortSides(SaleContractEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<Map<String,Object>> result = new PageResult(rowNum);
        if(user!=null){
            pageQuery.getQuery().put("types", user.getType()==null?0:user.getType());
        }
        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(),SaleContractEntity.class);
        List<Map<String,Object>> resultData=new ArrayList<>();
        if(pageQuery.getQuery().get("haveAuthority")!=null && pageQuery.getQuery().get("haveAuthority").equals("0")){
            String[] str={};
            result.setRecords(dao.queryCountByCondition(pageQuery.getQuery(), str,filters));
            var data=dao.queryPage(pageQuery.getQuery(), str,filters);
            for (var entity: data) {
                var info = infoDao.findBySN(entity.getSalerSN());
                var map=entity.toMap();
                var ss =   accountService.queryListConstruction(entity.getSn());
                if(ss!=null){
                    map.put("money",ss.getContractBalance());
                }
                if(info !=null){
                    map.put("salerPhone",info.getMobileNum());
                }else{
                    map.put("salerPhone","");
                }
                resultData.add(map);
            }
            result.setData(resultData);
        }else{
            result.setRecords(dao.queryCountByCondition(pageQuery.getQuery(), getTagSNs(),filters));
            var data=dao.queryPage(pageQuery.getQuery(), getTagSNs(),filters);
            for (var entity: data) {
                var map=entity.toMap();
                var ss =   accountService.queryListConstruction(entity.getSn());
                if(ss!=null){
                    map.put("money",ss.getContractBalance());
                }
                var productPriceRecord=productPriceAdjustDao.findLastAdjust(entity.getSn());
                var info = infoDao.findBySN(entity.getSalerSN());
                if(productPriceRecord !=null){
                    map.put("nowDiscount",productPriceRecord.getUnderFloatScale());
                }else{
                    map.put("nowDiscount","");
                }
                if(info !=null){
                    map.put("salerPhone",info.getMobileNum());
                }else{
                    map.put("salerPhone","");
                }
                resultData.add(map);
            }
            result.setData(resultData);
        }
        result.setPage(page);
        return result;
    }

    @Override
    public PageResult<SaleContractEntity> queryPageAll(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(SaleContractEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<SaleContractEntity> result = new PageResult(rowNum);
        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(),SaleContractEntity.class);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery(),new String[0],filters));
        result.setData(dao.queryPage(pageQuery.getQuery(),new String[0],filters));
        result.setPage(page);
        return result;
    }

    @Autowired
    ISaleContractProductsDao productsDao;
    @Override
    public PageResult<SaleContractEntity> queryPageSn(PageQuery pageQuery, int rowNum, int page, String productCateSn) {
        pageQuery.checkSortSides(SaleContractEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        PageResult<SaleContractEntity> result = new PageResult(rowNum);
        var filters = SearchFilterEngine.generateQueryList(pageQuery.getFilters(),SaleContractEntity.class);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery(), getTagSNs(),filters));
        result.setData(dao.queryPage(pageQuery.getQuery(), getTagSNs(),filters));
        result.setPage(page);
        return result;
    }

    @Override
    public Integer updateTruckPlate(String truckplate, String sn) {
        return dao.updateTruckPlate(truckplate,sn);
    }

    @Override
    public SaleContractEntity findBySn(String sn) {
        return dao.findBySN(sn);
    }

    @Override
    @Transactional
    public Integer saveSaleContract(Map<String, Object> model, String sn) throws Exception {
        int result;

        if (Tl.isEmpty(sn)) {
            //执行保存
            SaleContractEntity entity = new SaleContractEntity();
            Tl.getChangeLog(entity, model);
            createCustomerAndProject(entity);
            entity.setPYFieldValue();
            sn = queryNewSN(SaleContractEntity.class);
            entity.setOrganizationCode(getDepartSN());
            entity.setSn(sn);
            if (Tl.isEmpty(entity.getFilesPath())){
                entity.setFilesPath("[]");
            }

            result = dao.insertNew(entity);
            writeSaleTag(entity.getSn(),entity.getSalerSN(),entity.getSalerName(),null);
            if (result > 0) {
                var shareCode = writeUserTag(entity.getSn(), entity.getClass(), RelationType.CREATE.toString());
                saveGS(
                        entity.getSn(),
                        entity.getTitle(),
                        String.join(",",
                                entity.getTitle(),
                                entity.getCustomerName()
                        ),
                        entity,
                        HsApp.getCurrent() != null ? HsApp.getCurrent().getUserSN() : null,
                        shareCode
                );

                writeLog(ActionType.CREATE, entity.getSn(), "插入销售合同信息信息", Tl.toJson(entity), SaleContractEntity.class);
            }

        } else {
            //执行修改
            var entity = findBySn(sn);
            var backJson = entity.toJson();
            var oldSaleSN = entity.getSalerSN();
            var changeLog = Tl.getChangeLog(entity, model);
            createCustomerAndProject(entity);
            entity.setPYFieldValue();
            entity.setOrganizationCode(getDepartSN());
            if (Tl.isEmpty(entity.getFilesPath())){
                entity.setFilesPath("[]");
            }
            result = dao.update(entity);
            writeSaleTag(entity.getSn(),entity.getSalerSN(),entity.getSalerName(),oldSaleSN);
            if (result > 0) {

                saveGS(
                        entity.getSn(),
                        entity.getTitle(),
                        String.join(",",
                                entity.getTitle(),
                                entity.getCustomerName()
                        ),
                        entity,
                        HsApp.getCurrent().getUserSN(),
                        null
                );
                writeLog(ActionType.UPDATE, sn, changeLog, backJson, SaleContractEntity.class);
            }
        }

        //保存合同控制信息
        if (result > 0) {
            var data = model.get("controls");
            if (data != null) {
                List<Map<String, Object>> controls = (List<Map<String, Object>>) data;
                controlService.delete(sn);
                if (controls.size() > 0) {
                    Integer integer = controlService.saveContractControlInfo(controls, sn);
                    if (integer < 1) {
                        return 0;
                    }
                }
            }
        }
        return result;
    }

    private void writeSaleTag(String dataSN,String saleSN,String saleName,String oldSaleSN){
        if(oldSaleSN!=null && saleSN.equals(oldSaleSN))
        {
            return;
        }
        else if(oldSaleSN!=null && !"".equals(oldSaleSN))
        {
            tagsDao.deleteTagByTagSNAndMainSN(dataSN,oldSaleSN);
        }
        var mapCode = Tl.getDBMapCode(SaleContractEntity.class);
        var tag = new SaleSysTagsEntity();
        tag.setMainSN(dataSN);
        tag.setMainType(mapCode);
        tag.setTagSN(saleSN);
        tag.setTagTitle(saleName);

        tag.setTagType(Tl.getDBMapCode(UserInfoEntity.class));
        tag.setState((short) 0);
        tag.setRelationType(RelationType.OWNER.toString());
        tagsDao.insertNew(tag);

    }

    @Override
    @Transactional
    public Integer delete(String[] sn) {
        int result = 0;
        for (String s : sn) {
            controlService.delete(sn);
            var bySn = findBySn(s);
            bySn.setState((short) -1);
            result = +dao.update(bySn);
            deleteGs(sn);
        }
        return result;
    }

    @Override
    public Map<String, Object> queryDetailedBySN(String sn) {
        SaleContractEntity entity = dao.findBySN(sn);
        if (entity != null) {
            var entityMap = entity.toMap();
            entityMap.put("showControls", controlService.queryByContractSn(sn));
            return entityMap;
        }
        return null;
    }

    @Override
    public List<SaleContractEntity> queryBylistSn(List<String> sn) {
        if(sn.size()>0) {
            return dao.queryBylistSn(sn);
        }
        return new ArrayList<>();
    }

    @Override
    public Integer changeBySn(String[] snArray, short state) {
        int result=dao.changeBySn(snArray,state);
        if (result > 0) {
            forWriteLog(snArray,state);
        }
        return result;
    }

    @Override
    public PageResult<SaleContractEntity>  queryPageByProductCateSn(PageQuery query, Integer page, Integer rowNum) {
        query.checkSortSides(SaleContractEntity.class);
        query.getQuery().put("querySkip", (page - 1) * rowNum);
        query.getQuery().put("pageSize", rowNum);
        PageResult<SaleContractEntity> result = new PageResult(rowNum);
        var user = HsApp.getCurrent();
        if(user!=null){
            query.getQuery().put("types", user.getType()==null?0:user.getType());
        }
        var filters = SearchFilterEngine.generateQueryList(query.getFilters(),SaleContractEntity.class);
        result.setRecords(dao.queryPageSizeByProductCateSn(query.getQuery(),filters));
        result.setPage(page);
        result.setData(dao.queryPageByProductCateSn(query.getQuery(),filters));
        return result;

    }

    @Override
    public PageResult<SaleContractEntity> queryPageConstruction(PageQuery query, Integer page, Integer rowNum, String productCateSn) throws Exception {
        query.checkSortSides(SaleContractEntity.class);
        query.getQuery().put("querySkip", (page - 1) * rowNum);
        query.getQuery().put("pageSize", rowNum);
        PageResult<SaleContractEntity> result = new PageResult(rowNum);
        List<Map<String,Object>> filter=new ArrayList<>();
        var snList=getConstructionContractSN();
        if(snList.size()<=0){
            result=new PageResult<>(rowNum);
            return  result;
        }
        result.setRecords(dao.queryPageSizeConstruction(query.getQuery(),filter,productCateSn,snList));
        result.setPage(page);
        result.setData(dao.queryPageConstruction(query.getQuery(),filter,productCateSn,snList));
        return result;
    }

    @Override
    public List<SaleContractEntity> queryBySaleSn(String saleSn) {
        Map<String,Object> query = new HashMap<>();
        query.put("salerSN", saleSn);
        return dao.queryList(query);
    }

    @Override
    public PageResult<Map<String,Object>> queryCustomerContracts(PageQuery query, int rowNum, int page) throws Exception {
        query.checkSortSides(SaleContractEntity.class);
        query.getQuery().put("querySkip", (page - 1) * rowNum);
        query.getQuery().put("pageSize", rowNum);
        PageResult<Map<String,Object>> result = new PageResult(rowNum);
        var snList = getConstructionContractSN();
        if(snList.size()>0) {
            result.setRecords(dao.queryCountByCustom(query.getQuery(), snList));
            var cList  = dao.queryDataByCustom(query.getQuery(), snList);
            var users = customerUserDao.queryContractsUsers(snList,Tl.getDBMapCode(SaleContractEntity.class));
            users.add(getConstructionCurrent());
            var userFInfoList = linkerInfoDao.findLinkerBySN(users.stream().map(t->t.getLinkerSN()).toList());
            var nList = new ArrayList<Map<String,Object>>();
            for (var c:cList){
                var i = c.toMap();
                var cUsers = users.stream().filter(t->t.getObjSN().equals(c.getSn())).toList();
                var cUserSN = cUsers.stream().map(t->t.getLinkerSN()).toList();
                var uList = cUsers.stream().map(t->{
                    var st = new HashMap<String,String>();
                    st.put("sn",t.getSn());
                    st.put("userSN",t.getLinkerSN());
                    var uName = "";
                    var uOpt =  userFInfoList.stream().filter(o->o.getSn().equals(t.getLinkerSN())).findFirst();
                    if(!uOpt.isEmpty()){
                        uName = uOpt.get().getFullName();
                    }
                    st.put("name",uName);
                    return st;
                }).toList();

                i.put("users",uList);
                nList.add(i);
            }
            result.setData(nList);
        }
        else{
            result.setRecords(0);
            result.setData(new ArrayList<>());
        }
        result.setPage(page);
        return result;
    }

    /**
     * 创建客户信息和工地信息
     *
     * @param entity 销售合同信息
     * @return 执行结果
     * @throws Exception 保存异常
     */
    private Integer createCustomerAndProject(SaleContractEntity entity) throws Exception {
        Integer result = 0;
        //反向创建客户信息
        if (entity.getCustomerSN().equals(entity.getCustomerName())) {
            entity.setCustomerSN(customerService.saveCustomer(entity.getCustomerName()));
        }
        return result;
    }

}
